import tornado.ioloop
import tornado.web as web

import os
import json
import codecs

def reader_html2str(html_path):
    content = ''
    with codecs.open('templates/' + html_path, 'r', 'utf8') as r:
        for line in r.readlines():
            content += line
    return content

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write('hello world')

class IndexHandler(tornado.web.RequestHandler):
    '''
    处理一个请求
    '''
    def get(self):
        '''
        处理get
        :return:
        '''
        #self.render("index.html") # 返回一个html页面
        self.finish(reader_html2str('index.html'))

class LoginHandler(tornado.web.RequestHandler):
    def get(self):
        user_name = self.get_argument('user_name')
        user_pwd = self.get_argument('user_pwd')

        self.set_header('Content-Type', 'application/json; charset=UTF-8')
        self.write(json.dumps({'user_name':user_name, 'user_pwd':user_pwd, 'msg':'OK'}))
        self.finish()

def make_app():
    return tornado.web.Application([(r"/", MainHandler), # 处理http://10.133.105.166:9000 这个请求
                                    (r'/index', IndexHandler), # 处理http://10.133.105.166:9000/index
                                    (r'/login', LoginHandler)], # 处理http://10.133.105.166:9000/login 这个请求
                                   default_host='10.133.105.166',  # 指定绑定ip
                                   template_path = os.path.join(os.path.dirname(__file__), 'templates'), # 指定templates文件存放路径，我们放html文件
                                   static_path=os.path.join(os.path.dirname(__file__), 'static'), # 放js css image等文件
                                   debug=True)

if __name__=='__main__':
    app = make_app()
    app.listen(10000)
    tornado.ioloop.IOLoop.current().start()
